package com.java.springboot.elasticsearch.service;

import com.alibaba.fastjson.JSONObject;
import com.java.springboot.elasticsearch.entity.EsVO;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangtengfei
 * @date 2021/11/3 14:56
 */
@Slf4j
@Service
public class ElasticSearchServiceTmp {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    public List<String> queryByRest(String indices, Long startTime, Long endTime) {

        SearchRequest searchRequest = new SearchRequest(indices);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.query(convertParam(startTime, endTime));
        log.info("对index: {} 检索", indices);
        builder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        searchRequest.source(builder);
        SearchResponse searchResponse;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            log.info("检索结果数: {}", searchResponse.getHits().getTotalHits());
            log.info(searchResponse.toString());
            return convertResponse(searchResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private BoolQueryBuilder convertParam(Long startTime, Long endTime) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /**
         * range 查询
         */
        boolQueryBuilder.must(QueryBuilders.rangeQuery("@timestamp").lte(endTime).gte(startTime));
        /**
         * query_string 查询
         */
        boolQueryBuilder.must(QueryBuilders.queryStringQuery("message:" + "hello"));
        return boolQueryBuilder;
    }

    public List<String> convertResponse(SearchResponse response) {
        List<String> list = new ArrayList<>();
        if (response != null && response.getHits() != null) {
            for (SearchHit hit : response.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                EsVO esVO = JSONObject.parseObject(sourceAsString, EsVO.class);
                list.add(sourceAsString);
            }
        }
        return list;
    }
}
